//
//  JSUtil.swift
//  YoruNeko
//
//  Created by liphone on 2021/6/28.
//

import Foundation

class JSUtil{

    
    static var GET_FAVICON_SCRIPT = """
        var favicons = [];
        var nodeList = document.getElementsByTagName('link');
        for (var i = 0; i < nodeList.length; i++)
        {
            //判断节点属性
            if((nodeList[i].getAttribute('rel') == 'icon')||(nodeList[i].getAttribute('rel') == 'shortcut icon'))
            {
                const node = nodeList[i];
                favicons.push({
                    url: node.getAttribute('href'),
                    sizes: node.getAttribute('sizes')
                });
            }
        }
        favicons;
    """
    
    
    static func scriptForErrorPage(errorMsg:String)->String{
        return "changeErrorMessage('\(errorMsg)')"
    }
    
    
    static func scriptForAddImageOnClickedEvent()->String{
        if let fileUrl = Bundle.main.url(forResource: "add-onclick-to-img-and-callios", withExtension: "js"){
            if let js = try? String.init(contentsOf: fileUrl, encoding: .utf8){
                return js
            }
        }
       
        return """
            
            let imgObj = {
              src: "",
              width: 0,
              height: 0
            }

            let callIOS = window.webkit.messageHandlers.submitAnImageInfo.postMessage;
            // 获取所有父级dom元素
            function getParentTag(startTag, parentTagList = []) {
              // 传入标签是否是DOM对象
              if (!(startTag instanceof HTMLElement)) return console.error('receive only HTMLElement');
              // 父级标签是否是body,是着停止返回集合,反之继续
              if ('BODY' !== startTag.parentElement.nodeName) {
                // 放入集合
                parentTagList.push(startTag.parentElement)
                // 再上一层寻找
                return getParentTag(startTag.parentElement, parentTagList)
              }
              // 返回集合,结束
              else return parentTagList;

            }
            // 判断父级元素是否为链接
            function isLink(domObj) {
              let parents = getParentTag(domObj)
              for(let i = 0; i < parents.length; i++) {
                if(!!parents[i].href){
                  return true
                }
              }
              return false
            }
            // 点击后将当前图片信息传入IOS
            function clickEvent() {
               imgObj.src = this.src
               imgObj.width = this.naturalWidth
               imgObj.height = this.naturalHeight
               callIOS(imgObj)
            }
            // 为所有不为链接的图片加上点击事件
            function AddImgClickEvent() {
              let objs = document.getElementsByTagName("img");

              for (let i = 0; i < objs.length; i++) {
                !isLink(objs[i]) && objs[i].addEventListener('click', clickEvent)
              }
            }
            AddImgClickEvent();

            """
        
    }
    
}
